package com.atguigu.gmall.common.interceptor;

import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class FeignInterceptor implements RequestInterceptor {
    /*
    远程调用拦截器的执行方法
    @param :requestTemplate :马上要发出的远程调用 拦截下来 让他带上请求头信息再走 请求对象
    * */
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1获取当前微服务的请求对象 SpringIOC容器
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (null !=servletRequestAttributes){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if (null!=request){
                //2取出用户ID或临时用户ID
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                //3将上面的ID设置给马上要出发的请求对象RequestTemplate
                if (!StringUtils.isEmpty(userId)){
                    requestTemplate.header("userId",userId);
                }
                if (!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }

    }
}
